﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Utility;
using Sector7.Framework.Enums;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Medical.EntityType;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// SickRoomSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class SickRoomSummaryControl : AddModeControlBase
    {
        #region Accessor
        /// <summary>
        /// 病房信息
        /// </summary>
        public M7_SickRoom SickRoom
        {
            get { return m_entity as M7_SickRoom; }
            set { m_entity = value; }
        }
        #endregion
        #region Public functions
        #endregion

        #region Private functions

        /// <summary>
        /// Control Loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SickRoomSummaryControl_Loaded(object sender, RoutedEventArgs e)
        {
            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            SwitchPropertiyGroupsEnabledState(false);
            SwitchPropertiyActionButtonsState(CrudType.Unknown);
            SwitchActionButtonsState(false);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 读取所有病房信息列表
        /// </summary>
        private void GetData()
        {
            //1.获取所有病房信息列表
            m_roomList = Agent_INFS.GetSickRoomList();

            //2.获取所有二级科室列表
            m_subDeptList = Agent_INFS.GetDepartmentList(C_DepartmentFlags.SUB_DEPARTMENT); 
            m_tempRoomList.AddRange(m_roomList);
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            //加载所有病房信息列表
            ClientUtil.LoadItemsSource(dtgMain, m_tempRoomList);
            //加载所有二级科室列表
            ClientUtil.LoadItemsSource(cbbSubStorage, m_subDeptList);

            SwitchPropertiyActionButtonsStateByDataCount();

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isVisibility"></param>
        private void SwitchActionButtonsState(bool isVisibility)
        {
            Visibility visibility = isVisibility ? Visibility.Visible : Visibility.Hidden;
            btnOk.Visibility = visibility;
            btnCancel.Visibility = visibility;

            btnAdd.IsEnabled = !isVisibility;
            btnModify.IsEnabled = !isVisibility;
            btnDelete.IsEnabled = !isVisibility;
        }

        private void ClearSickRoomPropertity()
        {
            txbRoomtId.Text = "";
            txbRoomName.Text = "";
            txbSpellCode.Text = "";
            txbRemarks.Text = "";
            ckbIsValid.IsChecked = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isEnabled"></param>
        private void SwitchPropertiyGroupsEnabledState(bool isEnabled)
        {
            txbRoomtId.IsEnabled = false;
            txbRoomName.IsEnabled = isEnabled;
            txbSpellCode.IsEnabled = isEnabled;
            cbbSubStorage.IsEnabled = isEnabled;
            txbRemarks.IsEnabled = isEnabled;
            ckbIsValid.IsEnabled = isEnabled;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="crud"></param>
        private void SwitchPropertiyActionButtonsState(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Create:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
                case CrudType.Read:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = true;
                    btnDelete.IsEnabled = true;
                    break;
                default:
                    btnAdd.IsEnabled = false;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void SwitchPropertiyActionButtonsStateByDataCount()
        {
            if (m_roomList.Count == 0)
            {
                SwitchPropertiyActionButtonsState(CrudType.Create);
                ClearSickRoomPropertity();
            }
            else
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);
            }
        }

        /// <summary>
        /// 生成拼音码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSpellCode_Click(object sender, RoutedEventArgs e)
        {
            txbSpellCode.Text = CharacterUtil.GetSpellCodeString(txbRoomName.Text.Trim());
        }

        /// <summary>
        /// 数据表选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickRoom)
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);

                M7_SickRoom room = dtgMain.SelectedItem as M7_SickRoom;
                ShowSickRoomInfor(room);
            }
            else
            {
                SwitchPropertiyGroupsEnabledState(false);
                SwitchActionButtonsState(false);
                SwitchPropertiyActionButtonsStateByDataCount();
                ClearSickRoomPropertity();
            }
        }

        /// <summary>
        /// 显示SickRoom Infor
        /// </summary>
        /// <param name="area"></param>
        private void ShowSickRoomInfor(M7_SickRoom room)
        {
            if (room != null)
            {
                this.txbRoomtId.Text = room.RoomId.ToString();
                this.txbRoomName.Text = room.RoomName;
                this.txbSpellCode.Text = room.SpellCode;
                cbbSubStorage.SelectedValue = room.DeptId;
                this.txbRemarks.Text = room.Remarks;
                this.ckbIsValid.IsChecked = room.IsValid;
            }
            else
            {
                this.txbRoomtId.Text = null;
                this.txbRoomName.Text = null;
                this.txbSpellCode.Text = null;
                cbbSubStorage.SelectedValue = null;
                this.txbRemarks.Text = null;
                this.ckbIsValid.IsChecked = null;
            }
        }

        protected override bool CheckData()
        {
            m_errors.Clear();

            string roomName = txbRoomName.Text;
            string spellCode = txbSpellCode.Text;
            int departmentId = (cbbSubStorage.SelectedItem as M7_Department).DeptId;
            string remarks = txbRemarks.Text;
            bool isValid = (bool)ckbIsValid.IsChecked;

            if (string.IsNullOrEmpty(roomName))
            {
                m_errors.Add("病房名称", "不能为空!");
            }

            if (string.IsNullOrEmpty(spellCode))
            {
                m_errors.Add("拼音码", "不能为空!");
            }

            if (this.Crud == CrudType.Create)
            {
                SickRoom = new M7_SickRoom();
            }
            SickRoom.RoomName = roomName;
            SickRoom.SpellCode = spellCode;
            SickRoom.DeptId = departmentId;
            SickRoom.Remarks = remarks;
            SickRoom.IsValid = isValid;
            return base.CheckData();
        }

        protected override void AddData()
        {
            switch (m_crud)
            { 
                case CrudType.Create:
                    object roomIdObj = Agent_INFS.AddSickRoom(SickRoom); 
                    if (roomIdObj != null)
                    {
                        SickRoom.RoomId = Convert.ToInt32(roomIdObj);
                        m_roomList.Add(SickRoom);
                        m_tempRoomList.Add(SickRoom);
                        dtgMain.Items.Refresh();
                        SelectRoomItem(SickRoom); 
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
                case CrudType.Update:
                    bool isChanged = false;
                    var delta = GetDelta("RoomId", ref isChanged);
                    if (isChanged)
                    {
                        Agent_INFS.UpdateSickRoom(delta);
                        dtgMain.Items.Refresh();
                    }
                    SwitchPropertiyGroupsEnabledState(false);
                    SwitchActionButtonsState(false);
                    break;
            }
            base.AddData();
        }

        /// <summary>
        /// 选中Item颜色改变
        /// </summary>
        /// <param name="area"></param>
        private void SelectRoomItem(M7_SickRoom room)
        {
            if (dtgMain.Items.Contains(room))
            {
                dtgMain.SelectedItem = room;
            }
        }

        /// <summary>
        /// 初始化窗口
        /// </summary>
        /// <param name="crud">窗口操作类型</param>
        public new void InitializeControl(CrudType crud)
        {
            m_crud = crud;

            string prefix = string.Empty;
            switch (m_crud)
            {
                case CrudType.Create:
                    prefix = "新建";
                    InitializeForCreating();
                    break;
                case CrudType.Update:
                    prefix = "修改";
                    InitializeForUpdating();
                    break;
                default:
                    break;
            }

            InitializeForOthers();

            this.Tag = string.Format("{0}{1}", prefix, this.Tag);

            this.DataContext = m_entity;
        }

        /// <summary>
        /// 添加窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);
        }

        /// <summary>
        /// 初始化添加
        /// </summary>
        protected override void InitializeForCreating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ClearSickRoomPropertity();

            base.InitializeForCreating();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickRoom)
            {
                var room = dtgMain.SelectedItem as M7_SickRoom;
                SickRoom = room;
                InitializeControl(CrudType.Update);
            }
        }

        /// <summary>
        /// 初始化修改
        /// </summary>
        protected override void InitializeForUpdating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ShowSickRoomInfor(SickRoom);

            base.InitializeForUpdating();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem is M7_SickRoom)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除该病房?");
                if (mbr == MessageBoxResult.Yes)
                {
                    M7_SickRoom room = dtgMain.SelectedItem as M7_SickRoom;
                    int ret = Agent_INFS.DeleteSickRoom(room.RoomId);
                    if (ret > 0)
                    {
                        if (m_roomList.Contains(room))
                        {
                            int index = dtgMain.Items.IndexOf(room);
                            index++;

                            m_roomList.Remove(room);
                            dtgMain.Items.Refresh();

                            if (dtgMain.Items.Count != 0)
                            {
                                while (index >= dtgMain.Items.Count)
                                {
                                    index--;
                                }
                                dtgMain.SelectedIndex = index;
                            }
                        }

                        if (m_tempRoomList.Contains(room))
                        {
                            m_tempRoomList.Remove(room);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            SwitchPropertiyGroupsEnabledState(false);
            SwitchActionButtonsState(false);

            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_SickRoom)
            {
                M7_SickRoom room = dtgMain.SelectedItem as M7_SickRoom;
                ShowSickRoomInfor(room);
            }

            m_crud = CrudType.Unknown;
        }

        /// <summary>
        ///  Search关键值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsChanging(object sender, KeyEventArgs e)
        {
            string keywords = searchBox.Keywords;
            m_roomList = m_tempRoomList.FindAll(delegate(M7_SickRoom __sickRoom)
            {
                if (__sickRoom.RoomId.ToString().Contains(keywords) ||
                    __sickRoom.RoomName.Contains(keywords))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            ClientUtil.LoadItemsSource(dtgMain, m_roomList);
        }

        /// <summary>
        /// Search关键值重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsReset(object sender, EventArgs e)
        {
            m_roomList.Clear();
            m_roomList.AddRange(m_tempRoomList.ToArray());

            ClientUtil.LoadItemsSource(dtgMain, m_roomList);
        }
        #endregion


        #region Structure
        public SickRoomSummaryControl()
        {
            InitializeComponent();
        }
        #endregion

        #region Inner Members
        /// <summary>
        /// 病房信息列表
        /// </summary>
        private List<M7_SickRoom> m_roomList;

        /// <summary>
        /// 病房临时信息列表
        /// </summary>
        private List<M7_SickRoom> m_tempRoomList = new List<M7_SickRoom>();

        /// <summary>
        /// 获取所有二级科室列表
        /// </summary>
        private List<M7_Department> m_subDeptList;

        /// <summary>
        /// 获取所有临时二级科室列表
        /// </summary>
        private List<M7_Department> m_tempSubDeptList = new List<M7_Department>();
        #endregion
    }
}
